#include "oewalletmanage.h"
#include <QDir>
#include <QDebug>
#include <QSettings>
#include <QDateTime>


OEWalletManage::OEWalletManage(QObject *parent) : QObject(parent)
{
    // wallet info
    mapFileName_.insert("wallet", "wallet");
    // cryptographic seed
    mapFileName_.insert("seedname", "seed");
}

void OEWalletManage::clearWallet() {
    listInfo_.clear();
}

int OEWalletManage::loadWallet(const QString &_path) {
    // check path
    if (!QDir(_path).exists())
        return -87;

    // clean wallet
//    clearWallet();

    // set root path
    rootPath_ = _path;

    // load wallet info
    QStringList list_file_path = findWallet(_path);
    for (auto& filepath : list_file_path) {
        stWalletInfo info;
        if (0 != loadWalletInfo(filepath, info)) {
            qWarning() << QString("load %1 wallet error")
                            .arg(filepath);
        }
        listInfo_.push_back(info);
    }

    emit sigLoaded();

    return listInfo_.count();
}

int OEWalletManage::createWallet(
        const OEWalletManage::stWalletInfo &_info) {

    if (!QFile(_info.seedAbsPath).exists()
        || (!_info.absPath.isEmpty()
        && !QDir(_info.absPath).exists()))
        return -87;

    // get the path to create a wallet
    QString wallet_path = _info.absPath;
    if (_info.absPath.isEmpty()) {
        wallet_path = rootPath_ + "/" + _info.name;
    }

    // check wallet path
    if (QDir(wallet_path).exists()) {
        qDebug("create wallet error, because already exist.");
        return -183;
    }

    const QString& wallet_config = wallet_path + "/"
            + mapFileName_["wallet"];

    /// create wallet

    //[1] create folder
    QDir dir(wallet_path);
    dir.mkpath(wallet_path);

    //[2] create wallet config
    QSettings setting(wallet_config,QSettings::IniFormat);
    setting.beginGroup("INFO");
    setting.setValue("name", _info.name);
    setting.setValue("ek_pub_key", _info.ekPubKey);
    setting.setValue("status", "未分配");
    setting.setValue("create_time",
                     QDateTime::currentDateTime().
                     toString("yyyy-MM-dd hh:mm:ss"));
    setting.endGroup();

    //[3] move seed
    const QString& wallet_seed_path = wallet_path + "/"
            + mapFileName_["seedname"];
    QFile::rename(_info.seedAbsPath, wallet_seed_path);

    return 0;
}

OEWalletManage::stWalletInfo
    OEWalletManage::getWalletInfo(const QString &_pubKey)
{

    int ret_idx = listInfo_.indexOf(stWalletInfo("","",_pubKey));
    if (-1 == ret_idx) {
        return {};
    }
    return listInfo_.at(ret_idx);
}

const OEWalletManage::OEWalletList &OEWalletManage::getAllWallet()
{
    return listInfo_;
}

int OEWalletManage::size()
{
    return listInfo_.size();
}


int OEWalletManage::loadWalletInfo(const QString &_rootpath, OEWalletManage::stWalletInfo &_wallet)
{
    const QString& wallet_config = _rootpath + "/" + mapFileName_["wallet"];
    if (!QFile(wallet_config).exists()){
        return 87;
    }
    QSettings setting(wallet_config,QSettings::IniFormat);

    _wallet.absPath = _rootpath;

    _wallet.name = setting.value("INFO/name").toString();

    _wallet.ekPubKey = setting.value("INFO/ek_pub_key").toString();

    _wallet.status = setting.value("INFO/status").toString();

    _wallet.author = setting.value("INFO/author").toString();

    _wallet.crtTime = setting.value("INFO/create_time").toString();

    _wallet.seedAbsPath = _rootpath + "/audit.sr.seed";



#ifdef WALLET_NEED_LOGO
    // res
    _wallet.logo = setting.value("RES/logo").toString();
    convertPathToAbs(_rootpath, _wallet.logo);

    _wallet.logo_hover = setting.value("RES/logo_hover").toString();
    convertPathToAbs(_rootpath, _wallet.logo_hover);

    _wallet.logo_pressed = setting.value("RES/logo_pressed").toString();
    convertPathToAbs(_rootpath, _wallet.logo_pressed);
#endif



    return 0;
}

QStringList OEWalletManage::findWallet(const QString &_path)
{
    QDir dir(_path);
    if (!dir.exists())
        return {};

    // only dir
    dir.setFilter(QDir::Filter::Dirs |
                  QDir::Filter::NoDotAndDotDot);
    QFileInfoList list_dir = dir.entryInfoList();

    QStringList list_path;
    for (auto& dir_iter : list_dir) {
        bool bflag = isWallet(dir_iter.absoluteFilePath());
        if(bflag) {
            list_path.push_back(dir_iter.absoluteFilePath());
        }
    }
    return list_path;
}

bool OEWalletManage::convertPathToAbs(
        const QString &_rootPath, QString &_outpath)
{
    if (_outpath.isEmpty() || !QDir::isAbsolutePath(_rootPath))
        return false;

    if (QDir::isRelativePath(_outpath))
        _outpath = _rootPath + "/" + _outpath;

    return true;
}

bool OEWalletManage::isWallet(const QString &_path)
{
    const QString& filepath = _path + "/" + mapFileName_["wallet"];
    if (!QFileInfo(filepath).exists() || !QFileInfo(filepath).isFile())
        return false;
    return true;
}
